package com.hzcx.app.simplechat.util.token;

import android.content.Context;

import com.hzcx.app.simplechat.MyApplication;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.common.CommonSp;
import com.hzcx.app.simplechat.ui.friend.bean.FriendBean;
import com.hzcx.app.simplechat.ui.login.bean.LoginInfoBean;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.sp.SPUtils;

import org.litepal.LitePal;

/**
 * token工具类
 */
public class TokenUtils {

    private static final String TAG = TokenUtils.class.getSimpleName();

    /**
     * 返回请求的token值
     *
     * @return
     */
    public static String getTokenHeader() {
        return SPUtils.get(MyApplication.getContext(), CommonSp.USER_TOKEN, "").toString();
    }

    /**
     * 返回token是否过期或者用户信息是否设置完成
     *
     * @return
     */
    public static boolean isTokenExpire() {
        try {
            String token = (String) SPUtils.get(MyApplication.getContext(), CommonSp.USER_TOKEN, "");
            long time = (long) SPUtils.get(MyApplication.getContext(), CommonSp.USER_EXPIRETIME, 0L);
            int status = (int) SPUtils.get(MyApplication.getContext(), CommonSp.USER_STATUS, 0);
            int nowTime = (int) (System.currentTimeMillis() / 1000);
            LogUtils.d(TAG, "token:" + token + "    time:" + time + "    status:" + status + "    now:" + nowTime);
            if (EmptyUtils.isEmpty(token)) {
                // token为空，需要去登录
                return false;
            }
            if (nowTime >= time) {
                // token时间过期
                return false;
            }
            if (status != 1) {
                // 用户资料未完善
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 设置登录后的token信息
     *
     * @param bean
     */
    public static void setTokenInfo(LoginInfoBean bean) {
        SPUtils.put(MyApplication.getContext(), CommonSp.USER_TOKEN, bean.getToken());
        SPUtils.put(MyApplication.getContext(), CommonSp.USER_EXPIRETIME, bean.getExpiretime());
        SPUtils.put(MyApplication.getContext(), CommonSp.USER_STATUS, bean.getIs_perfect());
    }

    /**
     * 登出
     */
    public static void logout(Context context) {
        SPUtils.clear(context);
        LitePal.deleteAll(FriendBean.class);
        ChatUtil.getInstance().logOut();
    }
}
